package com.qingzhuge.limiter.support.impl;

import com.qingzhuge.limiter.dto.RateLimiterForm;
import com.qingzhuge.limiter.exception.RateLimiterException;
import com.qingzhuge.limiter.exception.RateLimiterParameterException;
import com.qingzhuge.limiter.support.RateLimiterCall;
import com.qingzhuge.limiter.support.RateLimiterCallback;
import com.qingzhuge.limiter.support.RateLimiterHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * @author zeroxiao
 * @date 2019/9/5 15:40
 */
@Slf4j
public class RateLimiterCallImpl implements RateLimiterCall {
    @Autowired
    private RateLimiterHandler handler;

    @Override
    public void call(Class<? extends RateLimiterCallback> callbackClass, RateLimiterForm form) throws RateLimiterException {
        if (form == null) {
            throw new RateLimiterParameterException();
        }
        if (StringUtils.isEmpty(form.getKey())) {
            throw new RateLimiterParameterException("field `key` Cannot be null");
        }
        if (StringUtils.isEmpty(form.getModule())) {
            throw new RateLimiterParameterException("field `module` Cannot be null");
        }
        handler.execute(callbackClass, form);
    }
}
